import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from './ui/card';
import { Button } from './ui/button';
import { Badge } from './ui/badge';
import { Progress } from './ui/progress';
import { Textarea } from './ui/textarea';
import { Lightbulb, Clock, Trophy, Star, Sparkles, Brain, Palette } from 'lucide-react';
import { motion, AnimatePresence } from 'motion/react';
import { TestResult } from '../types';
import { CreativeThinkingQuestion, CreativeResponse } from '../types/creativeThinking';
import { CREATIVE_THINKING_POOL } from '../constants/creativeThinking';

interface CreativeThinkingTestProps {
  onComplete: (result: TestResult) => void;
}

export function CreativeThinkingTest({ onComplete }: CreativeThinkingTestProps) {
  const [stage, setStage] = useState<'instructions' | 'test' | 'results'>('instructions');
  const [currentQuestion, setCurrentQuestion] = useState(0);
  const [selectedQuestions, setSelectedQuestions] = useState<CreativeThinkingQuestion[]>([]);
  const [responses, setResponses] = useState<CreativeResponse[]>([]);
  const [currentResponse, setCurrentResponse] = useState('');
  const [timeLeft, setTimeLeft] = useState(0);
  const [startTime, setStartTime] = useState<number>(0);
  const [questionStartTime, setQuestionStartTime] = useState<number>(0);
  const [score, setScore] = useState(0);
  const [showTransition, setShowTransition] = useState(false);

  const QUESTIONS_PER_TEST = 8;

  // 智能选择题目
  const selectRandomQuestions = () => {
    const shuffled = [...CREATIVE_THINKING_POOL].sort(() => Math.random() - 0.5);
    
    // 确保题目类型多样化
    const questionsByType: { [key: string]: CreativeThinkingQuestion[] } = {};
    
    shuffled.forEach(q => {
      if (!questionsByType[q.type]) {
        questionsByType[q.type] = [];
      }
      if (questionsByType[q.type].length < 1) {
        questionsByType[q.type].push(q);
      }
    });
    
    // 收集选中的题目
    const selected: CreativeThinkingQuestion[] = [];
    Object.values(questionsByType).forEach(typeQuestions => {
      selected.push(...typeQuestions);
    });
    
    // 如果不够8道，随机补充
    if (selected.length < QUESTIONS_PER_TEST) {
      const remaining = shuffled.filter(q => !selected.includes(q));
      const needed = QUESTIONS_PER_TEST - selected.length;
      selected.push(...remaining.slice(0, needed));
    }
    
    return selected.sort(() => Math.random() - 0.5).slice(0, QUESTIONS_PER_TEST);
  };

  // 评估创意回答
  const evaluateResponse = (response: string, question: CreativeThinkingQuestion): CreativeResponse => {
    const wordCount = response.trim().split(/\s+/).filter(word => word.length > 0).length;
    
    // 简单的评分算法（实际应用中可以使用更复杂的NLP分析）
    let creativity = 3; // 基础分
    let originality = 3;
    let relevance = 3;
    
    // 基于字数的评分调整
    if (wordCount > 100) creativity += 0.5;
    if (wordCount > 200) creativity += 0.5;
    
    // 基于关键词的原创性评分
    const uncommonWords = ['创新', '独特', '革命', '突破', '前所未有', '想象'];
    const uncommonWordCount = uncommonWords.filter(word => response.includes(word)).length;
    originality += uncommonWordCount * 0.3;
    
    // 基于问题类型的相关性评分
    if (question.type === 'divergent_thinking' && response.includes('用途')) relevance += 0.5;
    if (question.type === 'problem_solving' && response.includes('解决')) relevance += 0.5;
    if (question.type === 'story_creation' && wordCount > 50) relevance += 1;
    
    // 限制评分范围
    creativity = Math.min(5, Math.max(1, creativity));
    originality = Math.min(5, Math.max(1, originality));
    relevance = Math.min(5, Math.max(1, relevance));
    
    return {
      content: response,
      wordCount,
      submittedAt: Date.now(),
      creativity,
      originality,
      relevance
    };
  };

  useEffect(() => {
    let interval: NodeJS.Timeout;
    if (stage === 'test' && timeLeft > 0) {
      interval = setInterval(() => {
        setTimeLeft(prev => {
          if (prev <= 1) {
            handleSubmit();
            return 0;
          }
          return prev - 1;
        });
      }, 1000);
    }
    return () => clearInterval(interval);
  }, [stage, timeLeft]);

  useEffect(() => {
    if (stage === 'test' && selectedQuestions.length > 0) {
      const question = selectedQuestions[currentQuestion];
      setTimeLeft(question.timeLimit);
      setQuestionStartTime(Date.now());
    }
  }, [currentQuestion, stage]);

  const handleStartTest = () => {
    const questions = selectRandomQuestions();
    setSelectedQuestions(questions);
    setStage('test');
    setStartTime(Date.now());
  };

  const handleSubmit = () => {
    if (selectedQuestions.length === 0) return;
    
    const question = selectedQuestions[currentQuestion];
    const evaluatedResponse = evaluateResponse(currentResponse, question);
    
    setResponses(prev => [...prev, evaluatedResponse]);
    
    // 计算得分（基于三个维度的平均分）
    const questionScore = (evaluatedResponse.creativity + evaluatedResponse.originality + evaluatedResponse.relevance) / 3;
    setScore(prev => prev + questionScore);
    
    // 显示过渡动画
    setShowTransition(true);
    
    setTimeout(() => {
      setShowTransition(false);
      setCurrentResponse('');
      
      if (currentQuestion < selectedQuestions.length - 1) {
        setCurrentQuestion(prev => prev + 1);
      } else {
        setStage('results');
      }
    }, 2000);
  };

  const handleComplete = () => {
    const totalQuestions = selectedQuestions.length;
    const averageScore = score / totalQuestions;
    const finalScore = Math.round((averageScore / 5) * 100); // 转换为百分制
    const timeUsed = Math.round((Date.now() - startTime) / 1000);

    // 按题目类型统计
    const typeStats: { [key: string]: { 
      creativity: number; 
      originality: number; 
      relevance: number; 
      count: number;
      avgWords: number;
    } } = {};
    
    selectedQuestions.forEach((question, index) => {
      const type = question.type;
      const response = responses[index];
      
      if (!typeStats[type]) {
        typeStats[type] = { creativity: 0, originality: 0, relevance: 0, count: 0, avgWords: 0 };
      }
      
      if (response) {
        typeStats[type].creativity += response.creativity;
        typeStats[type].originality += response.originality;
        typeStats[type].relevance += response.relevance;
        typeStats[type].avgWords += response.wordCount;
        typeStats[type].count++;
      }
    });

    // 计算平均值
    Object.keys(typeStats).forEach(type => {
      const stats = typeStats[type];
      if (stats.count > 0) {
        stats.creativity = stats.creativity / stats.count;
        stats.originality = stats.originality / stats.count;
        stats.relevance = stats.relevance / stats.count;
        stats.avgWords = Math.round(stats.avgWords / stats.count);
      }
    });

    const result: TestResult = {
      id: Date.now().toString(),
      testType: 'creative-thinking',
      score: finalScore,
      completedAt: new Date(),
      duration: timeUsed,
      details: {
        totalQuestions,
        averageCreativity: Math.round(responses.reduce((sum, r) => sum + r.creativity, 0) / responses.length * 100) / 100,
        averageOriginality: Math.round(responses.reduce((sum, r) => sum + r.originality, 0) / responses.length * 100) / 100,
        averageRelevance: Math.round(responses.reduce((sum, r) => sum + r.relevance, 0) / responses.length * 100) / 100,
        totalWordCount: responses.reduce((sum, r) => sum + r.wordCount, 0),
        averageWordCount: Math.round(responses.reduce((sum, r) => sum + r.wordCount, 0) / responses.length),
        typeBreakdown: Object.entries(typeStats).map(([type, stats]) => ({
          type: this.getTypeDisplayName(type),
          creativity: Math.round(stats.creativity * 100) / 100,
          originality: Math.round(stats.originality * 100) / 100,
          relevance: Math.round(stats.relevance * 100) / 100,
          avgWords: stats.avgWords,
          count: stats.count
        })),
        questionsUsed: selectedQuestions.map(q => q.id),
        responses: responses.map(r => ({
          content: r.content.substring(0, 100) + (r.content.length > 100 ? '...' : ''),
          wordCount: r.wordCount,
          creativity: r.creativity,
          originality: r.originality,
          relevance: r.relevance
        }))
      }
    };

    onComplete(result);
  };

  const getTypeDisplayName = (type: string): string => {
    const typeMap: { [key: string]: string } = {
      divergent_thinking: '发散思维',
      problem_solving: '问题解决',
      story_creation: '故事创作',
      conceptual_combination: '概念融合',
      alternative_uses: '替代用途',
      hypothetical_scenarios: '假设情境',
      improvement_ideas: '改进构想',
      metaphorical_thinking: '比喻思维',
      design_challenge: '设计挑战',
      future_prediction: '未来预测',
      creative_naming: '创意命名',
      reverse_thinking: '逆向思维',
      invention_ideas: '发明创想',
      social_innovation: '社会创新',
      artistic_expression: '艺术表达',
      environmental_solutions: '环保方案',
      technology_application: '技术应用',
      cultural_fusion: '文化融合',
      educational_innovation: '教育创新',
      business_model: '商业模式'
    };
    return typeMap[type] || type;
  };

  if (stage === 'instructions') {
    return (
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        className="max-w-2xl mx-auto"
      >
        <Card className="bg-white/90 backdrop-blur-sm border-purple-200 shadow-lg">
          <CardHeader className="text-center pb-8">
            <div className="w-16 h-16 bg-gradient-to-br from-purple-600 to-pink-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg">
              <Lightbulb className="w-8 h-8 text-white" />
            </div>
            <CardTitle className="text-2xl text-slate-800">创造性思维测试</CardTitle>
            <p className="text-slate-600 mt-2">测试您的创意思维和创新能力</p>
          </CardHeader>
          
          <CardContent className="space-y-6">
            <div className="bg-gradient-to-r from-purple-50 to-pink-50 rounded-xl p-6 border border-purple-100">
              <h3 className="font-semibold text-purple-900 mb-4 flex items-center gap-2">
                <Star className="w-5 h-5" />
                测试说明
              </h3>
              <div className="space-y-3 text-slate-700">
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-purple-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">1</span>
                  <p>每道题都是开放性的创意挑战</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-purple-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">2</span>
                  <p>发挥想象力，给出独特、原创的回答</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-purple-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">3</span>
                  <p>没有标准答案，重点是创意和思维过程</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-purple-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">4</span>
                  <p>每题有时间限制，鼓励快速的创意迸发</p>
                </div>
              </div>
            </div>

            <div className="grid md:grid-cols-2 gap-4">
              <div className="bg-gradient-to-br from-blue-50 to-blue-100 rounded-xl p-4 border border-blue-200">
                <h4 className="font-semibold text-blue-800 mb-2 flex items-center gap-2">
                  <Brain className="w-4 h-4" />
                  发散思维
                </h4>
                <p className="text-sm text-blue-700">多角度思考，产生大量创意</p>
              </div>
              <div className="bg-gradient-to-br from-green-50 to-green-100 rounded-xl p-4 border border-green-200">
                <h4 className="font-semibold text-green-800 mb-2 flex items-center gap-2">
                  <Palette className="w-4 h-4" />
                  创意表达
                </h4>
                <p className="text-sm text-green-700">用文字展现独特的想象力</p>
              </div>
            </div>

            <div className="bg-gradient-to-r from-amber-50 to-orange-50 rounded-xl p-4 border border-amber-200">
              <h4 className="font-semibold text-amber-800 mb-2 flex items-center gap-2">
                <Sparkles className="w-4 h-4" />
                评分标准
              </h4>
              <div className="text-sm text-amber-700 space-y-1">
                <p><strong>创意度：</strong>想法的新颖性和独特性</p>
                <p><strong>原创性：</strong>思考的深度和独立性</p>
                <p><strong>相关性：</strong>回答与题目的契合程度</p>
              </div>
            </div>

            <div className="grid md:grid-cols-3 gap-4">
              <div className="text-center p-4 bg-gradient-to-br from-purple-50 to-purple-100 rounded-xl border border-purple-200">
                <div className="text-2xl font-bold text-purple-600 mb-1">20+</div>
                <div className="text-sm text-purple-700">创意场景</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-pink-50 to-pink-100 rounded-xl border border-pink-200">
                <div className="text-2xl font-bold text-pink-600 mb-1">8</div>
                <div className="text-sm text-pink-700">随机题目</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-purple-50 to-pink-50 rounded-xl border border-purple-200">
                <div className="text-2xl font-bold text-slate-600 mb-1">限时</div>
                <div className="text-sm text-slate-700">创意迸发</div>
              </div>
            </div>

            <Button 
              onClick={handleStartTest}
              className="w-full bg-gradient-to-r from-purple-600 to-pink-500 hover:from-purple-700 hover:to-pink-600 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
              size="lg"
            >
              开始创意之旅
            </Button>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  if (stage === 'test' && selectedQuestions.length > 0) {
    const question = selectedQuestions[currentQuestion];
    const progress = (currentQuestion / selectedQuestions.length) * 100;

    return (
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="max-w-4xl mx-auto space-y-6"
      >
        {/* 顶部状态栏 */}
        <div className="flex flex-col sm:flex-row gap-4 items-center justify-between">
          <div className="flex items-center gap-4">
            <Badge variant="outline" className="bg-purple-100 text-purple-700 border-purple-300">
              题目 {currentQuestion + 1} / {selectedQuestions.length}
            </Badge>
            <Badge variant="outline" className={`${
              question.difficulty === 'easy' ? 'bg-green-100 text-green-700 border-green-300' :
              question.difficulty === 'medium' ? 'bg-yellow-100 text-yellow-700 border-yellow-300' :
              'bg-red-100 text-red-700 border-red-300'
            }`}>
              {question.difficulty === 'easy' ? '简单' :
               question.difficulty === 'medium' ? '中等' : '困难'}
            </Badge>
            <Badge variant="outline" className="bg-pink-100 text-pink-700 border-pink-300">
              {question.category}
            </Badge>
          </div>
          
          <div className="flex items-center gap-2">
            <Clock className="w-4 h-4 text-slate-500" />
            <span className={`font-mono text-lg font-bold ${timeLeft <= 30 ? 'text-red-500' : 'text-slate-700'}`}>
              {Math.floor(timeLeft / 60)}:{(timeLeft % 60).toString().padStart(2, '0')}
            </span>
          </div>
        </div>

        <Progress value={progress} className="h-2" />

        {/* 题目区域 */}
        <Card className="bg-white/90 backdrop-blur-sm border-purple-200 shadow-lg">
          <CardHeader>
            <CardTitle className="text-xl text-slate-800 leading-relaxed">
              {question.prompt}
            </CardTitle>
            {question.evaluationCriteria.length > 0 && (
              <div className="flex flex-wrap gap-2 mt-3">
                <span className="text-sm text-slate-600">评分重点:</span>
                {question.evaluationCriteria.map((criteria, index) => (
                  <Badge key={index} variant="secondary" className="text-xs">
                    {criteria}
                  </Badge>
                ))}
              </div>
            )}
          </CardHeader>
          
          <CardContent className="space-y-6">
            <div className="space-y-4">
              <Textarea
                value={currentResponse}
                onChange={(e) => setCurrentResponse(e.target.value)}
                placeholder="在这里发挥您的创意想象..."
                className="min-h-[200px] text-base leading-relaxed resize-none border-purple-200 focus:border-purple-400"
                disabled={showTransition}
              />
              
              <div className="flex justify-between items-center text-sm text-slate-600">
                <span>
                  字数: {currentResponse.trim().split(/\s+/).filter(word => word.length > 0).length}
                </span>
                <span>
                  建议字数: {question.expectedCount > 1 ? `${question.expectedCount}个想法` : '100字以上'}
                </span>
              </div>
            </div>

            <Button
              onClick={handleSubmit}
              disabled={currentResponse.trim().length < 10 || showTransition}
              className="w-full bg-gradient-to-r from-purple-600 to-pink-500 hover:from-purple-700 hover:to-pink-600 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
              size="lg"
            >
              {showTransition ? '正在评估...' : '提交创意'}
            </Button>
          </CardContent>
        </Card>

        {/* 过渡动画 */}
        <AnimatePresence>
          {showTransition && (
            <motion.div
              initial={{ opacity: 0, scale: 0.8 }}
              animate={{ opacity: 1, scale: 1 }}
              exit={{ opacity: 0, scale: 0.8 }}
              className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center"
            >
              <Card className="bg-gradient-to-br from-purple-500 to-pink-500 text-white max-w-md mx-4">
                <CardContent className="p-8 text-center">
                  <motion.div
                    animate={{ rotate: 360 }}
                    transition={{ duration: 2, repeat: Infinity, ease: "linear" }}
                    className="w-16 h-16 mx-auto mb-4"
                  >
                    <Lightbulb className="w-full h-full" />
                  </motion.div>
                  <h3 className="text-xl font-semibold mb-2">创意评估中...</h3>
                  <p className="text-purple-100">正在分析您的创新思维</p>
                </CardContent>
              </Card>
            </motion.div>
          )}
        </AnimatePresence>
      </motion.div>
    );
  }

  if (stage === 'results') {
    const totalQuestions = selectedQuestions.length;
    const averageScore = score / totalQuestions;
    const finalScore = Math.round((averageScore / 5) * 100);
    const averageCreativity = responses.reduce((sum, r) => sum + r.creativity, 0) / responses.length;
    const averageOriginality = responses.reduce((sum, r) => sum + r.originality, 0) / responses.length;
    const totalWords = responses.reduce((sum, r) => sum + r.wordCount, 0);

    return (
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="max-w-2xl mx-auto"
      >
        <Card className="bg-white/90 backdrop-blur-sm border-purple-200 shadow-xl">
          <CardHeader className="text-center pb-6">
            <motion.div
              initial={{ scale: 0 }}
              animate={{ scale: 1 }}
              transition={{ delay: 0.2, type: "spring", stiffness: 200 }}
              className="w-20 h-20 bg-gradient-to-br from-purple-600 to-pink-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg"
            >
              <Trophy className="w-10 h-10 text-white" />
            </motion.div>
            
            <CardTitle className="text-3xl text-slate-800 mb-2">创意测试完成！</CardTitle>
            <div className="text-6xl font-bold bg-gradient-to-r from-purple-600 to-pink-500 bg-clip-text text-transparent">
              {finalScore}
            </div>
            <p className="text-slate-600">创造性思维评分</p>
          </CardHeader>
          
          <CardContent className="space-y-6">
            <div className="grid grid-cols-3 gap-4">
              <div className="text-center p-4 bg-gradient-to-br from-purple-50 to-purple-100 rounded-xl border border-purple-200">
                <div className="text-2xl font-bold text-purple-600 mb-1">
                  {Math.round(averageCreativity * 10) / 10}
                </div>
                <div className="text-sm text-purple-700">创意度</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-pink-50 to-pink-100 rounded-xl border border-pink-200">
                <div className="text-2xl font-bold text-pink-600 mb-1">
                  {Math.round(averageOriginality * 10) / 10}
                </div>
                <div className="text-sm text-pink-700">原创性</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-indigo-50 to-indigo-100 rounded-xl border border-indigo-200">
                <div className="text-2xl font-bold text-indigo-600 mb-1">{totalWords}</div>
                <div className="text-sm text-indigo-700">总字数</div>
              </div>
            </div>

            <Button 
              onClick={handleComplete}
              className="w-full bg-gradient-to-r from-purple-600 to-pink-500 hover:from-purple-700 hover:to-pink-600 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
              size="lg"
            >
              查看详细结果
            </Button>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  return null;
}